package com.lirh.mysql.config;

import com.lirh.mysql.entity.User1Entity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class MyRedisConfig {
//    @Bean
//    public RedisTemplate<Object,User1Entity> user1RedisTemplate(RedisConnectionFactory connectionFactory){
//        RedisTemplate<Object, User1Entity> redisTemplate = new RedisTemplate<>();
//        redisTemplate.setConnectionFactory(connectionFactory);
//        Jackson2JsonRedisSerializer<User1Entity> user1EntityJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(User1Entity.class);
//        redisTemplate.setDefaultSerializer(user1EntityJackson2JsonRedisSerializer);
//        return redisTemplate;
//    }
    @Bean
    public RedisCacheManager myredisCacheManager(RedisConnectionFactory factory){
        //初始化一个redisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory);
//        设置cachemanager的值序列化方式为json序列化
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(serializer);
        //设置过期时间
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(300)).serializeValuesWith(pair).disableCachingNullValues();



        //初始化RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);

    }
}
